package com.pansoft.request;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;


public class Serialize2SDcard {
	
	public static void serialize2SDcard(Object target,String file){
		
		createFile(file);
		
		FileOutputStream fos = null;
		ObjectOutputStream o = null;
		try {
			fos = new FileOutputStream(file);
			o = new ObjectOutputStream(fos);
			o.writeObject(target);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("没有找到文件！");
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(fos != null)
					fos.close();
				
				if(o != null)
					o.close();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	
	public static Object getObjectFromSDcard(String file){
		
		if(! new File(file).exists())
			return null;
		
		FileInputStream fis = null;
		ObjectInputStream in = null;
		try {
			fis = new FileInputStream(file);
			 in = new ObjectInputStream(fis);
			 
			 return in.readObject();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("没有找到文件！");
		} catch (StreamCorruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			
			try {
				fis.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	    
		return null;
	}
	
	public static void createFile(String path ){
		
		File file = new File(path);
		if(!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		if(!file.getParentFile().exists()){
			file.getParentFile().mkdirs();
		}
	}

}


